package app.maker.stock.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import app.maker.entity.Entrepot;
import app.maker.error.EntrepotException;
import app.maker.stock.intf.IEntrepot;

@Stateless(name = "daoEntrepot")
public class EntrepotImpl implements IEntrepot {
	@PersistenceContext
	private EntityManager em;

	public int updateEntrepot(Entrepot entrepot) throws EntrepotException {
		if (entrepot != null) {
			em.merge(entrepot);
			return entrepot.getIdEntrepot();
		} else {
			throw new EntrepotException("Entrepot non trouvé!");
		}
	}

	public void deleteEntrepot(Entrepot entrepot) throws EntrepotException {
		if (entrepot != null)
			em.remove(entrepot);
		else
			throw new EntrepotException("Entrepot non trouvé!");
	}

	public Entrepot getEntrepot(int id) throws EntrepotException {
		if (id > 0)
			return em.find(Entrepot.class, id);
		else
			throw new EntrepotException("Identifiant entrepot incorrect!");
	}

	public Entrepot getEntrepotByName(String name) throws EntrepotException {
		Entrepot entrepot = (Entrepot) em
				.createNamedQuery("Entrepot.findEntrepotByName")
				.setParameter("param", name).getSingleResult();
		if (entrepot != null)
			return entrepot;
		else
			throw new EntrepotException("Entrepot : " + name
					+ " inexistant !!!");
	}

	@SuppressWarnings("unchecked")
	public List<Entrepot> getAllEntrepot() {
		return em.createNamedQuery("Entrepot.findAll").getResultList();
	}

}
